<template>
  <div class="bar-chart-container">
    <div ref="barChart" class="bar-chart"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  props: {
    dataX: {
      type: Array,
      required: true
    },
    dataY: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      colorList: ['#0CB500', '#FFD634', '#01DAE2', '#FF5555', '#03B8DE', '#4AE879', '#FF8800', '#DBDBDB', '#ABEAFF'],
      option: {
        fontSize: 12,
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: 0,
          right: 0,
          top: 15,
          bottom: 0,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            interval: 0,
            rotate: 0,
            fontSize: 18,
            fontWeight: 1000
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#333'
            }
          },
          axisTick: {
            show: false
          },
          data: []
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '30%'],
          axisLine: {
            show: false,
            lineStyle: {
              color: '#333'
            }
          },
          axisLabel: {
            fontSize: 18
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: ['#307DCB'],
              width: 1,
              type: 'solid'
            }
          },
          axisTick: {
            show: false
          }
        },
        series: [
          {
            data: [],
            type: 'bar',
            itemStyle: {
              normal: {
                color: params => {
                  return this.colorList[params.dataIndex];
                },
                label: {
                  show: true,
                  position: 'top',
                  textStyle: {
                    color: '#333',
                    fontSize: 18
                  }
                }
              }
            }
          }
        ]
      }
    };
  },
  watch: {
    dataX: {
      handler(newDataX) {
        this.option.xAxis.data = newDataX;
        this.updateChart();
      },
      immediate: true
    },
    dataY: {
      handler(newDataY) {
        this.option.series[0].data = newDataY;
        this.updateChart();
      },
      immediate: true
    }
  },
  mounted() {
    this.renderChart();
  },
  methods: {
    renderChart() {
      this.chart = echarts.init(this.$refs.barChart);
      this.chart.setOption(this.option);
    },
    updateChart() {
      if (this.chart) {
        this.chart.setOption(this.option);
      }
    }
  }
};
</script>

<style scoped>
.bar-chart-container {
  width: 95%;
  height: 500px; /* 设置合适的高度 */
}
.bar-chart {
  width: 90%;
  height: 100%;
}
</style>
